export class LoginPage {
  private container: HTMLDivElement;

  constructor() {
    this.container = document.createElement('div');
    this.container.className = 'login-page';
    this.initContent();
    this.setupEventListeners();
  }

  private initContent() {
    this.container.innerHTML = `
      <div class="login-container">
        <!-- 背景装饰 -->
        <div class="login-background">
          <div class="floating-shapes">
            <div class="shape shape-1"></div>
            <div class="shape shape-2"></div>
            <div class="shape shape-3"></div>
            <div class="shape shape-4"></div>
          </div>
        </div>

        <!-- 登录表单 -->
        <div class="login-form-container">
          <div class="login-form">
            <!-- Logo区域 -->
            <div class="logo-section">
              <div class="logo">
                <span class="logo-icon">🚀</span>
                <h1 class="logo-text">ViteTest</h1>
              </div>
              <p class="welcome-text">欢迎回来！请登录您的账户</p>
            </div>

            <!-- 登录表单 -->
            <form class="login-form-content" id="loginForm">
              <div class="form-group">
                <label for="username" class="form-label">用户名</label>
                <div class="input-wrapper">
                  <span class="input-icon">👤</span>
                  <input 
                    type="text" 
                    id="username" 
                    name="username" 
                    class="form-input" 
                    placeholder="请输入用户名或邮箱"
                    required
                  >
                </div>
              </div>

              <div class="form-group">
                <label for="password" class="form-label">密码</label>
                <div class="input-wrapper">
                  <span class="input-icon">🔒</span>
                  <input 
                    type="password" 
                    id="password" 
                    name="password" 
                    class="form-input" 
                    placeholder="请输入密码"
                    required
                  >
                  <button type="button" class="password-toggle" id="passwordToggle">
                    👁️
                  </button>
                </div>
              </div>

              <div class="form-options">
                <label class="checkbox-wrapper">
                  <input type="checkbox" id="rememberMe" class="checkbox">
                  <span class="checkmark"></span>
                  记住我
                </label>
                <a href="#" class="forgot-password">忘记密码？</a>
              </div>

              <button type="submit" class="login-button" id="loginButton">
                <span class="button-text">登录</span>
                <span class="button-loading" style="display: none;">
                  <div class="spinner"></div>
                </span>
              </button>
            </form>

            <!-- 分割线 -->
            <div class="divider">
              <span class="divider-text">或</span>
            </div>

            <!-- 第三方登录 -->
            <div class="social-login">
              <button class="social-button wechat">
                <span class="social-icon">💬</span>
                <span class="social-text">微信登录</span>
              </button>
              <button class="social-button qq">
                <span class="social-icon">🐧</span>
                <span class="social-text">QQ登录</span>
              </button>
              <button class="social-button weibo">
                <span class="social-icon">📱</span>
                <span class="social-text">微博登录</span>
              </button>
            </div>

            <!-- 注册链接 -->
            <div class="register-section">
              <p class="register-text">
                还没有账户？ 
                <a href="#" class="register-link" id="registerLink">立即注册</a>
              </p>
            </div>
          </div>
        </div>

        <!-- 右侧信息面板 -->
        <div class="info-panel">
          <div class="info-content">
            <h2 class="info-title">欢迎使用 ViteTest</h2>
            <p class="info-description">
              这是一个现代化的前端开发项目，集成了 Vite 和 Webpack 两种构建工具，
              提供完整的开发体验和性能优化方案。
            </p>
            <div class="feature-list">
              <div class="feature-item">
                <span class="feature-icon">⚡</span>
                <span class="feature-text">快速构建</span>
              </div>
              <div class="feature-item">
                <span class="feature-icon">🔧</span>
                <span class="feature-text">灵活配置</span>
              </div>
              <div class="feature-item">
                <span class="feature-icon">📊</span>
                <span class="feature-text">性能分析</span>
              </div>
              <div class="feature-item">
                <span class="feature-icon">🛡️</span>
                <span class="feature-text">安全可靠</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    `;

    this.addStyles();
  }

  private addStyles() {
    if (!document.getElementById('login-page-styles')) {
      const style = document.createElement('style');
      style.id = 'login-page-styles';
      style.textContent = `
        .login-page {
          min-height: 100vh;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }

        .login-container {
          display: flex;
          min-height: 100vh;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          position: relative;
          overflow: hidden;
        }

        /* 背景装饰 */
        .login-background {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          z-index: 1;
        }

        .floating-shapes {
          position: relative;
          width: 100%;
          height: 100%;
        }

        .shape {
          position: absolute;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.1);
          animation: float 6s ease-in-out infinite;
        }

        .shape-1 {
          width: 80px;
          height: 80px;
          top: 20%;
          left: 10%;
          animation-delay: 0s;
        }

        .shape-2 {
          width: 120px;
          height: 120px;
          top: 60%;
          right: 15%;
          animation-delay: 2s;
        }

        .shape-3 {
          width: 60px;
          height: 60px;
          bottom: 20%;
          left: 20%;
          animation-delay: 4s;
        }

        .shape-4 {
          width: 100px;
          height: 100px;
          top: 10%;
          right: 30%;
          animation-delay: 1s;
        }

        @keyframes float {
          0%, 100% { transform: translateY(0px) rotate(0deg); }
          50% { transform: translateY(-20px) rotate(180deg); }
        }

        /* 登录表单容器 */
        .login-form-container {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 2rem;
          z-index: 2;
        }

        .login-form {
          background: rgba(255, 255, 255, 0.95);
          backdrop-filter: blur(10px);
          border-radius: 20px;
          padding: 3rem;
          width: 100%;
          max-width: 450px;
          box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.2);
        }

        /* Logo区域 */
        .logo-section {
          text-align: center;
          margin-bottom: 2rem;
        }

        .logo {
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 1rem;
        }

        .logo-icon {
          font-size: 2.5rem;
          margin-right: 0.5rem;
        }

        .logo-text {
          font-size: 2rem;
          font-weight: bold;
          background: linear-gradient(135deg, #667eea, #764ba2);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          margin: 0;
        }

        .welcome-text {
          color: #666;
          font-size: 1rem;
          margin: 0;
        }

        /* 表单样式 */
        .form-group {
          margin-bottom: 1.5rem;
        }

        .form-label {
          display: block;
          margin-bottom: 0.5rem;
          color: #333;
          font-weight: 500;
          font-size: 0.9rem;
        }

        .input-wrapper {
          position: relative;
          display: flex;
          align-items: center;
        }

        .input-icon {
          position: absolute;
          left: 1rem;
          color: #999;
          font-size: 1.1rem;
          z-index: 1;
        }

        .form-input {
          width: 100%;
          padding: 1rem 1rem 1rem 3rem;
          border: 2px solid #e1e5e9;
          border-radius: 12px;
          font-size: 1rem;
          transition: all 0.3s ease;
          background: white;
        }

        .form-input:focus {
          outline: none;
          border-color: #667eea;
          box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .password-toggle {
          position: absolute;
          right: 1rem;
          background: none;
          border: none;
          cursor: pointer;
          font-size: 1.1rem;
          color: #999;
          z-index: 1;
        }

        /* 表单选项 */
        .form-options {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 2rem;
        }

        .checkbox-wrapper {
          display: flex;
          align-items: center;
          cursor: pointer;
          font-size: 0.9rem;
          color: #666;
        }

        .checkbox {
          margin-right: 0.5rem;
        }

        .forgot-password {
          color: #667eea;
          text-decoration: none;
          font-size: 0.9rem;
        }

        .forgot-password:hover {
          text-decoration: underline;
        }

        /* 登录按钮 */
        .login-button {
          width: 100%;
          padding: 1rem;
          background: linear-gradient(135deg, #667eea, #764ba2);
          color: white;
          border: none;
          border-radius: 12px;
          font-size: 1.1rem;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          position: relative;
          overflow: hidden;
        }

        .login-button:hover {
          transform: translateY(-2px);
          box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .login-button:active {
          transform: translateY(0);
        }

        .button-loading {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }

        .spinner {
          width: 20px;
          height: 20px;
          border: 2px solid rgba(255, 255, 255, 0.3);
          border-top: 2px solid white;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        /* 分割线 */
        .divider {
          text-align: center;
          margin: 2rem 0;
          position: relative;
        }

        .divider::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 0;
          right: 0;
          height: 1px;
          background: #e1e5e9;
        }

        .divider-text {
          background: rgba(255, 255, 255, 0.95);
          padding: 0 1rem;
          color: #999;
          font-size: 0.9rem;
        }

        /* 第三方登录 */
        .social-login {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 1rem;
          margin-bottom: 2rem;
        }

        .social-button {
          display: flex;
          flex-direction: column;
          align-items: center;
          padding: 1rem;
          border: 2px solid #e1e5e9;
          border-radius: 12px;
          background: white;
          cursor: pointer;
          transition: all 0.3s ease;
        }

        .social-button:hover {
          border-color: #667eea;
          transform: translateY(-2px);
        }

        .social-icon {
          font-size: 1.5rem;
          margin-bottom: 0.5rem;
        }

        .social-text {
          font-size: 0.8rem;
          color: #666;
        }

        /* 注册区域 */
        .register-section {
          text-align: center;
        }

        .register-text {
          color: #666;
          font-size: 0.9rem;
          margin: 0;
        }

        .register-link {
          color: #667eea;
          text-decoration: none;
          font-weight: 600;
        }

        .register-link:hover {
          text-decoration: underline;
        }

        /* 信息面板 */
        .info-panel {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 2rem;
          z-index: 2;
        }

        .info-content {
          color: white;
          max-width: 500px;
        }

        .info-title {
          font-size: 2.5rem;
          font-weight: bold;
          margin-bottom: 1rem;
        }

        .info-description {
          font-size: 1.1rem;
          line-height: 1.6;
          margin-bottom: 2rem;
          opacity: 0.9;
        }

        .feature-list {
          display: grid;
          grid-template-columns: repeat(2, 1fr);
          gap: 1rem;
        }

        .feature-item {
          display: flex;
          align-items: center;
          padding: 1rem;
          background: rgba(255, 255, 255, 0.1);
          border-radius: 12px;
          backdrop-filter: blur(10px);
        }

        .feature-icon {
          font-size: 1.5rem;
          margin-right: 0.5rem;
        }

        .feature-text {
          font-weight: 500;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
          .login-container {
            flex-direction: column;
          }

          .info-panel {
            display: none;
          }

          .login-form {
            padding: 2rem;
          }

          .social-login {
            grid-template-columns: 1fr;
          }
        }
      `;
      document.head.appendChild(style);
    }
  }

  private setupEventListeners() {
    // 密码显示/隐藏切换
    const passwordToggle = this.container.querySelector('#passwordToggle') as HTMLButtonElement;
    const passwordInput = this.container.querySelector('#password') as HTMLInputElement;
    
    if (passwordToggle && passwordInput) {
      passwordToggle.addEventListener('click', () => {
        const type = passwordInput.type === 'password' ? 'text' : 'password';
        passwordInput.type = type;
        passwordToggle.textContent = type === 'password' ? '👁️' : '🙈';
      });
    }

    // 登录表单提交
    const loginForm = this.container.querySelector('#loginForm') as HTMLFormElement;
    const loginButton = this.container.querySelector('#loginButton') as HTMLButtonElement;
    
    if (loginForm && loginButton) {
      loginForm.addEventListener('submit', (e) => {
        e.preventDefault();
        this.handleLogin();
      });
    }

    // 注册链接
    const registerLink = this.container.querySelector('#registerLink') as HTMLAnchorElement;
    if (registerLink) {
      registerLink.addEventListener('click', (e) => {
        e.preventDefault();
        this.handleRegister();
      });
    }

    // 第三方登录按钮
    const socialButtons = this.container.querySelectorAll('.social-button');
    socialButtons.forEach(button => {
      button.addEventListener('click', () => {
        this.handleSocialLogin(button.className);
      });
    });
  }

  private async handleLogin() {
    const username = (this.container.querySelector('#username') as HTMLInputElement)?.value;
    const password = (this.container.querySelector('#password') as HTMLInputElement)?.value;
    const rememberMe = (this.container.querySelector('#rememberMe') as HTMLInputElement)?.checked;

    if (!username || !password) {
      this.showMessage('请填写完整的登录信息', 'error');
      return;
    }

    // 显示加载状态
    this.showLoading(true);

    try {
      // 调用后端登录API
      const response = await fetch('http://localhost:8080/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          password,
          rememberMe
        })
      });

      const result = await response.json();

      if (result.success) {
        // 保存token到localStorage
        localStorage.setItem('accessToken', result.data.token);
        localStorage.setItem('refreshToken', result.data.refreshToken);
        localStorage.setItem('userInfo', JSON.stringify(result.data.userInfo));

        this.showMessage('登录成功！', 'success');
        
        // 跳转到主页
        setTimeout(() => {
          this.navigateToHome();
        }, 1000);
      } else {
        this.showMessage(result.message || '登录失败', 'error');
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      this.showMessage('网络错误，请检查后端服务是否启动', 'error');
    } finally {
      this.showLoading(false);
    }
  }

  private handleRegister() {
    this.showMessage('注册功能开发中...', 'info');
  }

  private handleSocialLogin(type: string) {
    this.showMessage(`${type}登录功能开发中...`, 'info');
  }

  private showLoading(show: boolean) {
    const button = this.container.querySelector('#loginButton') as HTMLButtonElement;
    const buttonText = this.container.querySelector('.button-text') as HTMLSpanElement;
    const buttonLoading = this.container.querySelector('.button-loading') as HTMLSpanElement;

    if (button && buttonText && buttonLoading) {
      if (show) {
        button.disabled = true;
        buttonText.style.display = 'none';
        buttonLoading.style.display = 'block';
      } else {
        button.disabled = false;
        buttonText.style.display = 'block';
        buttonLoading.style.display = 'none';
      }
    }
  }

  private showMessage(message: string, type: 'success' | 'error' | 'info') {
    // 创建消息提示
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    messageDiv.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 1rem 1.5rem;
      border-radius: 8px;
      color: white;
      font-weight: 500;
      z-index: 1000;
      animation: slideIn 0.3s ease;
      background: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6'};
    `;

    document.body.appendChild(messageDiv);

    // 3秒后自动移除
    setTimeout(() => {
      messageDiv.remove();
    }, 3000);
  }

  private navigateToHome() {
    // 这里可以添加路由跳转逻辑
    console.log('跳转到主页');
  }

  public render(): HTMLElement {
    return this.container;
  }
} 